package com.steakliu.sun.scanner;

import com.steakliu.sun.annotation.SunService;
import com.steakliu.sun.common.helper.SunServiceHelper;
import com.steakliu.sun.common.meta.ServiceMeta;
import com.steakliu.sun.common.util.ServiceUtil;
import com.steakliu.sun.registry.api.RegistryService;
import com.steakliu.sun.server.api.ServerLocalServiceCaches;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能说明：
 * <p>
 * Original @Author: steakliu-刘牌, 2022-12-10  18:48
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
public class SunServiceScanner extends ClassScanner {

    private static final Logger LOGGER = LoggerFactory.getLogger(SunServiceScanner.class);

    public static Map<String, ServerLocalServiceCaches> scanner(String host, int port, String scanPackage, RegistryService registryService) throws Exception {
        Map<String, ServerLocalServiceCaches> localCacheServices = new HashMap<>();
        List<String> classNameList = getClassNameList(scanPackage);
        if (classNameList.isEmpty()) {
            return localCacheServices;
        }
        for (String className : classNameList) {
            Class<?> clazz = Class.forName(className);
            SunService sunService = clazz.getAnnotation(SunService.class);
            if (sunService != null) {
                String serviceName = ServiceUtil.getServiceName(sunService);
                LOGGER.info("注册服务，服务名为:  {}", serviceName);
                String version = sunService.version();
                String group = sunService.group();
                String tag = sunService.tag();
                int weight = sunService.weight();
                String token = sunService.token();
                //注册服务到注册中心
                ServiceMeta serviceMeta = new ServiceMeta(serviceName, host, port, version, group, tag, weight);
                registryService.register(serviceMeta);
                //将服务存储进本地缓存
                String key = SunServiceHelper.getServiceKey(serviceName, version, group);
                ServerLocalServiceCaches serverLocalServiceCaches = new ServerLocalServiceCaches();
                serverLocalServiceCaches.setServiceBean(clazz.newInstance());
                serverLocalServiceCaches.setToken(token);
                localCacheServices.put(key, serverLocalServiceCaches);
            }
        }
        return localCacheServices;
    }

}
